import time,redis,json
import jwt
from django.utils.deprecation import MiddlewareMixin
from django.http import JsonResponse
from medical import settings


class PermissionsMiddleware(MiddlewareMixin):
    def process_request(self,request):
        r = redis.StrictRedis('localhost', 6379, charset="utf-8", decode_responses=True, db=0)
        # 定义白名单
        white_list = ['/logins/']
        # 获取token
        url = request.path
        print(url)
        if url not in white_list:
            try:
                token = request.headers.get('Authorization')
                print(token)
                data = jwt.decode(token,settings.SECRET_KEY,algorithms='HS256')
                print(data)
                # 解析验证
                # 是否过期
                if data['exp'] < int(time.time()):
                    print('------------')
                    return JsonResponse({'code':10001,'msg':'过期'})
                # 是否退出
                # 是否有接口权限
                print('00000000000000000')
                plist = json.loads(r.get('resourceinterface'))
                print(plist)
                if plist:
                    if url not in plist:
                        return JsonResponse({'code':10002,'msg':'没有权限'})
            except Exception as e:
                print(e)
                return JsonResponse({'code':10003,'msg':'token失效'})